﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using EFCodeCreater.Module;
using MyAddin;

namespace EFCodeCreater
{
    public partial class Form2 : Form
    {
        private IContainer components = null;

        private TreeView treeView1;

        private Button button1;

        private FolderBrowserDialog folderBrowserDialog1;

        public SqlConnection TrainConnection
        {
            get;
            set;
        }
        public string databsename
        {
            get;
            set;
        }
        public string dbtype
        {
            get;
            set;
        }
        public Form2()
        {
            this.InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            Form2_LoadForSql();
        }

        public List<TableInfo> Tableinfo = new List<TableInfo>();
        private void Form2_LoadForSql()
        {
            string selectCommandText = "select d.name,f.value from sysobjects d left join sys.extended_properties f on d.id=f.major_id and f.minor_id=0 where type='U' order by name";
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(selectCommandText, this.TrainConnection);
            var tableDataSet = new DataSet();
            sqlDataAdapter.Fill(tableDataSet, "ds1");
            foreach (DataRow dataRow in tableDataSet.Tables[0].Rows)
            {
                TreeNode node = new TreeNode
                {
                    Text = dataRow["name"].ToString(),
                };
                Tableinfo.Add(new TableInfo()
                {
                    name= dataRow["name"].ToString(),
                    value = string.IsNullOrEmpty(dataRow["value"]?.ToString()) ? dataRow["name"].ToString() : dataRow["value"].ToString()
                });
                this.treeView1.Nodes.Add(node);
            }
            this.TrainConnection.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.folderBrowserDialog1.ShowDialog();
            List<string> list = (from TreeNode node in this.treeView1.Nodes
                                 where node.Checked
                                 select node.Text).ToList<string>();
            if (!list.Any())
            {
                MessageBox.Show(@"请确保已经选择了至少一张表");
                return;
            }
            var tables= Tableinfo.Where(x => list.Contains(x.name)).ToList();
            CreateLogic(tables);
            MessageBox.Show("生成完成");
            Application.Exit();
        }

        public void CreateLogic(List<TableInfo> list)
        {
            var root = folderBrowserDialog1.SelectedPath;
            var dbset = new List<string>();
            foreach (var currentTable in list)
            {
                var table = Tool.GetTableInfo(currentTable.name, TrainConnection);
                CreateService.Create(currentTable,TemplateCode.I_name_Service,TemplateCode._name_Service, root);
                CreateDomain.Create(table, currentTable, TemplateCode.I_name_DomainService,TemplateCode._name_DomainService,TemplateCode.I_name_Repository,TemplateCode._name_ListSpecification, root);
                CreateRepository.Create(table,currentTable, TemplateCode._name_Repository, root);
                CreateModel.Create(table, currentTable, root, TemplateCode._name_1,TemplateCode._name_CreateInput,TemplateCode._name_UpdateInput,TemplateCode._name_ListInput,TemplateCode._name_ListDto);
               dbset.Add($@"public DbSet<{currentTable.name}> {currentTable.name} {{ get; set; }}");
            }
            File.AppendAllLines(root + @"\EF实体对象引用.txt", dbset);
        }
        
        private void label1_Click(object sender, EventArgs e)
        {
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && this.components != null)
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.treeView1 = new System.Windows.Forms.TreeView();
            this.button1 = new System.Windows.Forms.Button();
            this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
            this.SuspendLayout();
            // 
            // treeView1
            // 
            this.treeView1.CheckBoxes = true;
            this.treeView1.Location = new System.Drawing.Point(12, 52);
            this.treeView1.Name = "treeView1";
            this.treeView1.Size = new System.Drawing.Size(424, 295);
            this.treeView1.TabIndex = 2;
            this.treeView1.DoubleClick += new System.EventHandler(this.treeView1_DoubleClick);
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(361, 353);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 3;
            this.button1.Text = "生成";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form2
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(448, 391);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.treeView1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "Form2";
            this.ShowIcon = false;
            this.Text = "生成框架类";
            this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form2_FormClosed);
            this.Load += new System.EventHandler(this.Form2_Load);
            this.ResumeLayout(false);

        }

        private bool show = true;

        private void treeView1_DoubleClick(object sender, EventArgs e)
        {
            if (show)
            {
                foreach (TreeNode item in treeView1.Nodes)
                {
                    item.Checked = true;
                }
                show = false;
            }
            else
            {
                foreach (TreeNode item in treeView1.Nodes)
                {
                    item.Checked = false;
                }
                show = true;
            }
        }

        private void label1_Click_1(object sender, EventArgs e)
        {

        }

        private void label1_Click_2(object sender, EventArgs e)
        {

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }
    }

    public class DataCoulmnDTO
    {
        public string Name { get; set; }
        public string DisplayName { get; set; }
        public Type PropertyType { get; set; }
        public int? MaxLength { get; set; }
    }

    public class TableInfo
    {
        public string name { get; set; }
        public string value { get; set; }
    }
}
